
#include <QtGui/QPen>
#include <math.h>
#include "connection.h"


CConnection::CConnection(CStation *startItem, CStation *endItem,
						 QGraphicsItem *parent, QGraphicsScene *scene)
			:QGraphicsLineItem(parent, scene)
{
	m_begin = startItem;
    m_finish = endItem;
    setFlag(QGraphicsItem::ItemIsSelectable, true);
	m_color = Qt::blue;
    setPen(QPen(m_color, 2, Qt::SolidLine, Qt::RoundCap, Qt::RoundJoin));
}


CConnection::~CConnection(void)
{
}


 QRectF CConnection::boundingRect() const
 {
    qreal extra = (pen().width() + 20) / 2.0;

    return QRectF(line().p1(), QSizeF(line().p2().x() - line().p1().x(),
                                       line().p2().y() - line().p1().y()))
		         .normalized()
                 .adjusted(-extra, -extra, extra, extra);
 }

 QPainterPath CConnection::shape() const
 {
     QPainterPath path = QGraphicsLineItem::shape();
     return path;
 }

 void CConnection::updatePosition()
 {
     QLineF line(mapFromItem(m_begin, 0, 0), mapFromItem(m_finish, 0, 0));
     setLine(line);
 }

 void CConnection::paint(QPainter *painter, const QStyleOptionGraphicsItem *,
           QWidget *)
 {
    if (m_begin->collidesWithItem(m_finish))
        return;

    QPen myPen = pen();
    myPen.setColor(m_color);
    painter->setPen(myPen);
    painter->setBrush(m_color);

    QLineF centerLine(m_begin->pos(), m_finish->pos());
	setLine(centerLine);
	/*
    QPolygonF endPolygon = m_finish->polygon();
    QPointF p1 = endPolygon.first() + m_finish->pos();
    QPointF p2;
    QPointF intersectPoint;
    QLineF polyLine;
    for (int i = 1; i < endPolygon.count(); ++i) {
		p2 = endPolygon.at(i) + m_finish->pos();
		polyLine = QLineF(p1, p2);
		QLineF::IntersectType intersectType =
			polyLine.intersect(centerLine, &intersectPoint);
		if (intersectType == QLineF::BoundedIntersection)
			break;
			p1 = p2;
    }
	
    setLine(QLineF(intersectPoint, m_begin->pos()));

    double angle = ::acos(line().dx() / line().length());
    if (line().dy() >= 0)
        angle = (M_PI * 2) - angle;
    */
      
    painter->drawLine(line());
    if (isSelected()) {
        painter->setPen(QPen(m_color, 1, Qt::DashLine));
		QLineF myLine = line();
		myLine.translate(0, 4.0);
		painter->drawLine(myLine);
		myLine.translate(0,-8.0);
		painter->drawLine(myLine);
	}
 }